/**
 * 雷达图
 */
import React from 'react';
import { Radar, RadarOptions } from '@antv/g2plot';
import { DL_TYPE, WD_TYPE, THEME_COLOR } from 'src/pages/AnalyseManage/EditReport/components/EditorDataType/EnumConfig';
import { getComponentData } from 'src/services/AnalyseManage';
import { isNumber } from 'src/libs/utils';

import { message } from 'antd';
import { ChartService, IProps } from 'src/pages/AnalyseManage/EditReport/components/ChartsType/components/ChartService';
import { CHART_LINK } from 'src/pages/AnalyseManage/EditReport/topics';
import PubSub from 'pubsub-js';

const DEFAULT_DATA = [
	{ category: 'cate', name: 'G2', value: 10178 },
	{ category: 'cate', name: 'G6', value: 7077 },
	{ category: 'cate', name: 'F2', value: 7345 },
	{ category: 'cate', name: 'L7', value: 2029 },
	{ category: 'cate', name: 'X6', value: 298 },
	{ category: 'cate', name: 'AVA', value: 806 },
];

export default class RadarChart extends ChartService {

	state = {
		chartEl: null,
		data: [],
		xField: 'name',
		yField: 'value',
		seriesField: 'category',
		xAlias: 'name',
		yAlias: 'value',
		eventToken: [],
		dependencies: [],	//	图表联动参数
		isRender: false
	};

	getConfig = (): RadarOptions => {
		const { config = {} } = this.props;
		const { style = {} } = config;
		// console.log( style );
		return {
			autoFit: true,
			data: this.state.data,
			xField: this.state.xField,
			yField: this.state.yField,
			color: ( config.style.customBlockColor || [] ).map( v => v.color ).concat( THEME_COLOR ),
			seriesField: this.state.seriesField,
			meta: {
				name: {
					alias: this.state.xAlias,
				},
				value: {
					alias: this.state.yAlias,
					formatter: ( data ) => {
						return data;
					}
				},
			},
			appendPadding: [
				style.chartTopPadding || 10,
				style.chartRightPadding || 0,
				style.chartBottomPadding || 0,
				style.chartLeftPadding || 0
			],
			padding: 'auto',
			legend: style.isShowLegend === true ?
				{
					position: style.legendPosition,
					itemName: {
						style: {
							fill: style.legendFontColor || '#333',
							fontSize: style.legendFontSize || 15,
							fontFamily: style.legendFontFamily || 'SimSun',
							fontWeight: style.legendFontBold ? 'bold' : 'normal',
							fontStyle: style.legendFontItalic ? 'italic' : 'normal',
						},
					},
				} : false,
			label: style.isShowLabelData ?
				{
					position: style.chartLabelPosition || 'top', // 'top', 'bottom', 'middle',
					style: {
						fontFamily: style.labelFontFamily || 'SimSun',
						fontSize: style.labelFontSize || 15,
						fontWeight: style.labelFontBold ? 'bold' : 'normal',
						fontStyle: style.labelFontItalic ? 'italic' : 'normal',
						fill: style.labelFontColor || '#333',
					},
					formatter: ( data ) => {
						let { value, precision = '', dataUnit = '' } = data;
						const valueList = this.state.data.map( t => t.value );
						const maxValue = valueList.reduce( ( acc, cur ) => acc > cur ? acc : cur );
						const minValue = valueList.reduce( ( acc, cur ) => acc > cur ? cur : acc );
						if (
							( style.onlyShowLabelMax && data.value === maxValue ) ||
							( style.onlyShowLabelMin && data.value === minValue ) ||
							( !style.onlyShowLabelMax && !style.onlyShowLabelMin )
						) {
							value = isNumber( precision ) ? value.toFixed( precision ) : value;
							return `${value}${dataUnit}`;
						}
					}
				} : null,
			tooltip: this.getToolTipConfig( style ),
			xAxis: {
				tickLine: null,
				line: {
					style: {
						stroke: style.chartGridlineColor ,
					},
				},
				
				grid: {
					line: {
						style: {
							stroke: style.chartLineColor,
						},
					},
				}
			},
			yAxis: {
				label: false,
				// grid: {
				// 	alternateColor: 'rgba(0, 0, 0, 0.04)',
				// },
				grid: {
					alternateColor: 'rgba(0, 0, 0, 0.04)',
					line: {
						style: {
							stroke: style.chartGridlineColor,
						},
					},
				}
			},
			// 开启辅助点
			point: {
				size: 4,
			},
			area: {},
		};
	}

	// 设置tooltip
	getToolTipConfig = ( style ) => {
		return style.isShowToolTip
			? {
				// 设置toolTip相关样式
				domStyles: {
					'g2-tooltip-list-item': {
						fontSize: `${style.tooltipFontSize || '12'}px`,
						color: style.tooltipFontColor || '#333',
						fontFamily: style.tooltipFontFamily || 'SimSun',
						fontWeight: style.tooltipFontBold ? 'bold' : 'normal',
						fontStyle: style.tooltipFontItalic ? 'italic' : 'normal',
					},
					'g2-tooltip-title': {
						fontSize: `${style.tooltipFontSize || '12'}px`,
						color: style.tooltipFontColor || '#333',
						fontFamily: style.tooltipFontFamily || 'SimSun',
						fontWeight: style.tooltipFontBold ? 'bold' : 'normal',
						fontStyle: style.tooltipFontItalic ? 'italic' : 'normal',
					},
				},
				// showMarkers: true,
				showContent: true,
				follow: true,
				fields: [	this.state.xField, this.state.yField, this.state.seriesField, 'dataUnit', 'precision' ],
				formatter: ( datum ) => {
					let value = isNumber( datum.precision ) ? datum.value.toFixed( datum.precision ) : datum.value;
					return { name: datum.category, value: `${value}${datum.dataUnit || ''}` };
				},
				showCrosshairs: true,
				crosshairs: {
					line: {
						style: {
							lineDash: [ 4, 5 ],
							stroke: '#86BC25'
						}
					}
				}
			}
			: {
				// showMarkers: false,
				showContent: false,
				domStyles: null,
				follow: false,
			};
	};

	// 入参构建
	itemInfo = ( v ) => {
		return {
			aggregateType: v.modelType === DL_TYPE ? v.aggregateType : '', //	度量的聚合类型
			formatType: v.modelType === WD_TYPE ? v.formatType : '', // 维度的聚合类型v.
			alias: v.title.trim(),
			dataType: v.dataType,
			frontendId: '',
			id: v.name,
			orderType: v.orderType, // 排序方式
			quota: v.modelType === WD_TYPE ? 'WD' : 'DL',
			symbol: '',
			type: v.type,
			value: '',
			dataUnit: v.dataUnit,
			precision: v.precision
		};
	};

	async getConditionData() {
		const { config = {} } = this.props;
		const { xAxis = [], yAxis = [], series = [] } = config.data;
		// console.log( config );
		if ( xAxis.length && yAxis.length ) {
			const x = xAxis.map( v => this.itemInfo( v ) );
			const y = yAxis.map( v => this.itemInfo( v ) );
			const category = series.map( v => this.itemInfo( v ) );
			// const conditions = this.props.config.data.filterFields ? this.props.config.data.filterFields.map( v => v.filterConditions ).flat() : [];
			// 内部筛选 condition
			const filterFieldCondition = this.props.config.data.filterFields
				? this.props.config.data.filterFields.map( ( v ) => v.filterConditions ).flat()
				: [];

			// 筛选组件的 condition
			let filterCompConditions = this.props.config.data.filterConditions || {};
			let newFilterCompConditions = [];
			Object.keys( filterCompConditions ).forEach( ( key ) => {
				newFilterCompConditions = newFilterCompConditions.concat( filterCompConditions[key] );
			} );

			const request = {
				dataConfig: {
					dataModel: {
						pageId: this.props.pageId,
						tableName: config.data.tableCode,
						x,
						y,
						category,
						conditions: filterFieldCondition.concat( this.state.dependencies, newFilterCompConditions )
					},
					needAutoRefresh: true,
					tableType: 'radar'
				},
				type: 'bar',
				tenantCode: this.props.tenantCode
			};
			let pageResponse = await getComponentData( request );
			if ( pageResponse.data ) {
				const { rows = [] } = pageResponse.data.data || {};
				if ( pageResponse.data.success && rows && rows.length > 0 ) {
					// const newRows = transformDataUnitData( rows, y, 'value' );

					return rows;
				}
			}
		}
		return DEFAULT_DATA;
	}

	shouldComponentUpdate( nextProps: Readonly<IProps>, nextState: Readonly<{ dependencies: any }>, nextContext: any ): boolean {
		if ( JSON.stringify( nextProps ) !== JSON.stringify( this.props ) ||
			JSON.stringify( this.state.dependencies ) !== JSON.stringify( nextState.dependencies ) ) return true;
		return false;
	}

	getSnapshotBeforeUpdate( prevProps: Readonly<IProps>, prevState: Readonly<{ dependencies: any }> ): any | null {
		let { config, chartLayout } = this.props;
		let changeObj = Object.create( null );
		const { xAxis = [], yAxis = [], series = [], filterFields = [] } = config.data || {};
		const { xAxis: pxAxis = [], yAxis: pyAxis = [], 
			series: pSeries = [], filterFields: pfilterFields = [] } = prevProps.config.data || {};

		//	判断数据字段是否变化了
		if ( ( xAxis.length && yAxis.length ) &&
			( JSON.stringify( pxAxis ) !== JSON.stringify( xAxis ) ||
				JSON.stringify( pyAxis ) !== JSON.stringify( yAxis ) ||
				JSON.stringify( pSeries ) !== JSON.stringify( series ) ||
				JSON.stringify( pfilterFields ) !== JSON.stringify( filterFields ) ||
				JSON.stringify( prevState.dependencies ) !== JSON.stringify( this.state.dependencies ) ||
				JSON.stringify( config.data.filterConditions ) !== JSON.stringify( prevProps.config.data.filterConditions ) ) ) {
			if ( yAxis.length > 1 && series.length > 0 ) {
				message.error( '外圈、颜色都绑定了字段时，只能绑定一个指标字段' );
			} else {
				changeObj.needDataChange = true;
			}
		}

		//	判断样式是否改变
		if ( JSON.stringify( prevProps.config.style ) !== JSON.stringify( config.style ) ) {
			changeObj.needStyleChange = true;
		}

		//判断是否因宽高改变重新适应布局
		if ( prevProps.chartLayout.w !== chartLayout.w || prevProps.chartLayout.h !== chartLayout.h ) {
			changeObj.needLayoutChange = true;
		}

		return changeObj;
	}

	initEvent = async () => {
		const resData = await this.getConditionData();
		const { xAxis = [], yAxis = [] } = this.props.config.data;
		const xAlias = xAxis.map( t => t.title ).join( '-' ) || 'name';
		const yAlias = yAxis.map( t => t.title ).join( '-' ) || 'value';
		this.setState( {
			data: resData,
			xAlias,
			yAlias
		}, () => {
			const chart = new Radar( this.props.id, this.getConfig() );
			chart.render();
			this.setState( {
				chartEl: chart,
				isRender: true
			} );

			//	数据联动 组装联动参数
			chart.on( 'element:click', ( ev ) => {
				if( !this.props.config.mutual.isChainAvailable ) return;

				const intervalElement = ev.target.get( 'element' );
				if( intervalElement.shapeType !== 'hollow-circle' ) return;	//	点击小圆圈才生效
				const data = intervalElement.getModel().data; // 单条数据
				console.log( data );
				const dimension = this.props.config.data.xAxis;
				if( !dimension || dimension.length === 0 ) return;
				const dependencies = dimension.map( ( item, index ) => {
					return {
						formatType: item.formatType,
						id: [ item.name ],
						quota: item.modelType === WD_TYPE ? 'WD' : 'DL',
						symbol: 'EQ',
						value: [ data.name ]		//	从原数据中找到item，一一对应字段
					};
				} );

				PubSub.publish( CHART_LINK, {
					publisherId: this.props.id,
					listenerIds: this.props.config.mutual.chartsChainIds,
					dimension: dependencies,
					tableCode: this.props.config.data.tableCode
				} );
			} );
		} );
	};

	async componentDidUpdate( prevProps: Readonly<IProps>, prevState: Readonly<{}>, snapshot?: any ) {
		// console.log( 'column', snapshot );

		// const { columnType } = this.props.config.data || {};
		if ( snapshot.needStyleChange ) this.state.chartEl.update( this.getConfig() );

		if ( snapshot.needDataChange ) {
			// console.log( this.state.data );
			const { xAxis = [], yAxis = [] } = this.props.config.data;
			const xAlias = xAxis.map( t => t.title ).join( '-' ) || 'name';
			const yAlias = yAxis.map( t => t.title ).join( '-' ) || 'value';
			const resData = await this.getConditionData();
			this.setState( {
				data: resData,
				xAlias,
				yAlias
			}, () => {
				this.state.chartEl.changeData( this.state.data );
			} );
		}

	}

	render() {
		return <div id={this.props.id} style={{ height: '100%' }}></div>;
	}
};
